<template>
  <CommonPage show-footer title="预约记录">
    <template #action>
      <div>
        <n-button type="primary" secondary @click="$table?.handleExport()">
          <TheIcon icon="mdi:download" :size="18" class="mr-5" />
          导出
        </n-button>
        <n-button type="primary" class="ml-16" @click="handleAdd">
          <TheIcon icon="material-symbols:add" :size="18" class="mr-5" />
          新建预约记录
        </n-button>
      </div>
    </template>

    <CrudTable
      ref="$table"
      v-model:query-items="queryItems"
      :extra-params="extraParams"
      :scroll-x="1200"
      :columns="columns"
      :get-data="getBookingHistorys"
      @on-checked="onChecked"
      @on-data-change="(data) => (tableData = data)"
    >
      <template #queryBar>
        <QueryBarItem label="医生姓名" :label-width="65">
          <n-input
            v-model:value="queryItems.doctorName"
            type="text"
            placeholder="请输入医生姓名"
            @keypress.enter="$table?.handleSearch"
          />
        </QueryBarItem>
        <QueryBarItem label="患者姓名" :label-width="65">
          <n-input
            v-model:value="queryItems.name"
            type="text"
            placeholder="请输入患者姓名"
            @keypress.enter="$table?.handleSearch"
          />
        </QueryBarItem>
      </template>
    </CrudTable>
    <!-- 新增/编辑/查看 -->
    <CrudModal
      v-model:visible="modalVisible"
      :title="modalTitle"
      :loading="modalLoading"
      :show-footer="modalAction !== 'view'"
      @on-save="handleSave"
    >
      <n-form
        ref="modalFormRef"
        label-placement="left"
        label-align="left"
        :label-width="80"
        :model="modalForm"
        :disabled="modalAction === 'view'"
      >
        <n-form-item
          label="患者姓名"
          path="card.name"
          :rule="{
            required: true,
            message: '请输入患者姓名',
            trigger: ['input', 'blur'],
          }"
        >
          <n-input v-model:value="modalForm.card.name" placeholder="请输入患者姓名" />
        </n-form-item>
        <n-form-item
          label="证件类型"
          path="card.id_type"
          :rule="{
            required: true,
            message: '请输入证件类型',
            trigger: ['input', 'blur'],
          }"
        >
          <n-input v-model:value="modalForm.card.id_type" placeholder="请输入证件类型" />
        </n-form-item>
        <n-form-item
          label="证件号码"
          path="card.id_number"
          :rule="{
            required: true,
            message: '请输入证件号码',
            trigger: ['input', 'blur'],
          }"
        >
          <n-input v-model:value="modalForm.card.id_number" placeholder="请输入证件号码" />
        </n-form-item>
        <n-form-item
          label="电话号码"
          path="card.phone"
          :rule="{
            required: true,
            message: '请输入电话号码',
            trigger: ['input', 'blur'],
          }"
        >
          <n-input v-model:value="modalForm.card.phone" placeholder="请输入电话号码" />
        </n-form-item>
        <n-form-item
          label="预约医生"
          path="doctor.nickname"
          :rule="{
            required: true,
            message: '请输入预约医生',
            trigger: ['input', 'blur'],
          }"
        >
          <n-input v-model:value="modalForm.doctor.nickname" placeholder="请输入预约医生" />
        </n-form-item>
        <n-form-item
          label="预约科室"
          path="department.dept_name"
          :rule="{
            required: true,
            message: '请输入预约科室',
            trigger: ['input', 'blur'],
          }"
        >
          <n-input v-model:value="modalForm.department.dept_name" placeholder="请输入预约科室" />
        </n-form-item>
        <n-form-item
          label="预约时间"
          path="ticket.day"
          :rule="{
            required: true,
            message: '请输入预约时间',
            trigger: ['input', 'blur'],
          }"
        >
          <n-input v-model:value="modalForm.ticket.day" placeholder="请输入预约时间" />
        </n-form-item>
      </n-form>
    </CrudModal>
  </CommonPage>
</template>

<script setup>
import { NButton, NSwitch } from 'naive-ui'
import { formatDateTime, renderIcon, isNullOrUndef } from '@/utils'
import { useCRUD } from '@/composables'
import api from './api'
defineOptions({ name: 'Booking' })
const $table = ref(null)
/** 表格数据，触发搜索的时候会更新这个值 */
const tableData = ref([])
/** QueryBar筛选参数（可选） */
const queryItems = ref({})
/** 补充参数（可选） */
const extraParams = ref({})
var deptId = 0

onActivated(async () => {
  const user = await api.getUser()
  const { department_id } = user.data
  deptId = department_id

  $table.value?.handleSearch()
  modalForm.card = {}
  modalForm.doctor = {}
  modalForm.schedule = {}
  modalForm.ticket = {}
  modalForm.department = {}
})


const columns = [
  { title: '患者姓名', key: 'card.name', width: 50, ellipsis: { tooltip: true } },
  { title: '证件类型', key: 'card.id_type', width: 50, ellipsis: { tooltip: true } },
  { title: '证件号码', key: 'card.id_number', width: 50, ellipsis: { tooltip: true } },
  { title: '电话号码', key: 'card.phone', width: 50, ellipsis: { tooltip: true } },
  { title: '预约医生', key: 'doctor.nickname', width: 50, ellipsis: { tooltip: true } },
  { title: '预约时间', key: 'ticket.day', width: 50, ellipsis: { tooltip: true } },
  {
    title: '操作',
    key: 'actions',
    width: 60,
    align: 'center',
    fixed: 'right',
    hideInExcel: true,
    render(row) {
      return [
        h(
          NButton,
          {
            size: 'small',
            type: 'primary',
            secondary: true,
            onClick: () => handleView(row),
          },
          { default: () => '查看', icon: renderIcon('majesticons:eye-line', { size: 14 }) }
        ),

        h(
          NButton,
          {
            size: 'small',
            type: 'error',
            style: 'margin-left: 15px;',
            onClick: () => handleDelete(row.id),
          },
          {
            default: () => '删除',
            icon: renderIcon('material-symbols:delete-outline', { size: 14 }),
          }
        ),
      ]
    },
  },
]

// 选中事件
function onChecked(rowKeys) {
  if (rowKeys.length) $message.info(`选中${rowKeys.join(' ')}`)
}

// 发布
function handlePublish(row) {
  if (isNullOrUndef(row.id)) return

  row.publishing = true
  setTimeout(() => {
    row.isPublish = !row.isPublish
    row.publishing = false
    $message?.success(row.isPublish ? '已发布' : '已取消发布')
  }, 1000)
}
function getBookingHistorys(params = {}) {
  return api.getBookingHistorys(params,deptId)
}

const {
  modalVisible,
  modalAction,
  modalTitle,
  modalLoading,
  handleAdd,
  handleDelete,
  handleEdit,
  handleView,
  handleSave,
  modalForm,
  modalFormRef,
} = useCRUD({
  name: '预约记录',
  initForm: { author: '大脸怪' },
  doCreate: api.addPost,
  doDelete: api.deleteDepartment,
  doUpdate: api.updateDepartment,
  refresh: () => $table.value?.handleSearch(),
})
</script>